const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const koaBody = require('koa-body');//解析上传文件的插件
const cors = require('koa2-cors')
const Router = require('koa-router');
const log4js = require('./app/middleware/log4');
const requireDirectory = require('require-directory');//遍历routes目录引入路由
// error handler
onerror(app)
// middlewares
app.use(json())
app.use(require('koa-static')(__dirname + '/app/public'))
app.use(koaBody({
  enableTypes: ['json', 'form', 'text', 'file'],
  multipart: true,
  formidable: {
    maxFileSize: 2000 * 1024 * 1024    // 设置上传文件大小最大限制，默认2M
  }
}));
app.use(cors({
  origin: function (ctx) {
    return '*';//设置ip、域名白名单
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE', 'PUT'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
// logger
app.use(async (ctx, next) => {
  const start = new Date();//响应开始时间
  let ms;//响应间隔时间
  try {
    await next();//开始进入到下一个中间件
    ms = new Date() - start;
    console.log(`---------START_TIME=>${start}------------`)
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
    console.log(`---------END_TIME=>${new Date}-----------`)
    log4js.logResponse(ctx, ms);//记录响应日志
  } catch (error) {
    ms = new Date() - start;
    log4js.logError(ctx, error, ms);//记录异常日志
  }
});
requireDirectory(module, './routes', { visit: whenLoadModule });// routes
function whenLoadModule(obj) {
  if (obj instanceof Router) {
    app.use(obj.routes(), obj.allowedMethods());
  }
}
// error-handling
app.on('error', (err, ctx) => {
  const start = new Date();//响应开始时间
  ms = new Date() - start;
  log4js.logError(ctx, err, ms);
  console.error('server error', err, ctx)
});
module.exports = app
